from code.engine import engine

class UploadRules:

    def __init__(self):
        self.ruleMap = {}
        self.defaultRule = SimpleUploadRule()
        
    def putRule(self,modelType,rule):
        self.ruleMap[modelType] = rule
        
    def getRule(self,modelType):
        return self.ruleMap.get(modelType,self.defaultRule)

class abstractUploadRule :
    
    def getUploadPath(self,modelType,param):
        pass
    
    def getRenamedName(self,modelType,param,filename):
        pass

class SimpleUploadRule(abstractUploadRule):
    
    def getUploadPath(self,modelType,param):
        manager = engine.manager
        dic = manager.getDic(modelType)
        if not dic:
            raise "modelType:" + modelType + "does not exists!"
        uppath = dic.upload
        if not uppath:
            raise "modelType:" + modelType + "does not have upload path"
        return uppath
    
    def getRenamedName(self,modelType,param,filename):
        return filename

class ItemUploadRule(abstractUploadRule):
    
    def __init__(self):
        self.typeIdSubDirMap = {}
        manager = engine.manager
        selector = manager.getSelector(11)
        for key,value in selector.subdirs.items():
            self.typeIdSubDirMap[key] = value
            
    def getUploadPath(self,modelType,param):
        manager = engine.manager
        dic = manager.getDic(modelType)
        if not dic:
            raise "modelType:" + modelType + "does not exists!"
        uppath = dic.upload
        if not uppath:
            raise "modelType:" + modelType + "does not have upload path"
        if not param:
            raise "item subdir param not given!"
        typeId = int(param)
        subpath = self.typeIdSubDirMap[typeId]
        return uppath + "/" + subpath
    
    def getRenamedName(self,modelType,param,filename):
        return filename

uploadRules = UploadRules()
uploadRules.putRule("item", ItemUploadRule())